package com.exce;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * @Author WaveHi
 * @Date 20/8/2021 下午 9:20
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
public class GetCount {

    public static void main(String[] args) {

        FileReader fr1 = null;
        try{

            //获取数据读取的位置
            File destFile1 = new File("day11/data/chars.txt");

            //获取输入流
            fr1 = new FileReader(destFile1);

            //接收数据
            StringBuilder sb1 = new StringBuilder((int)destFile1.length());

            //接收读取的数据
            char[] cbuf = new char[10];

            //获取读取数据的长度
            int len = 0;

            //读取数据
            while((len = fr1.read(cbuf)) != -1) {

                sb1.append(new String(cbuf,0,len));

            }

            //获取集合对象
            TreeMap<Character,Integer> tm = new TreeMap();

            //拆分数据为单个字符
            char[] chars = new String(sb1).toCharArray();

            //循环统计
            for(char c : chars) {

                Character cUp = Character.valueOf(c);

                if(tm.containsKey(cUp)) {

                    tm.put(cUp,tm.get(cUp) + 1);

                }else {

                    tm.put(cUp,1);

                }

            }

            //输出统计结果
            //标记数据
            int count = 0;
            Set<Map.Entry<Character,Integer>> entrys = tm.entrySet();
            for(Map.Entry entry : entrys) {

                if(count == entrys.size() - 1) {

                    System.out.print(entry.getKey() + "(" + entry.getValue() + ")");

                }else {

                    System.out.print(entry.getKey() + "(" + entry.getValue() + ")" + ",");

                }
                count++;

            }

        }catch(IOException e) {

            e.printStackTrace();

        }finally {

            //资源的关闭
            if(fr1 != null) {

                try{

                    fr1.close();

                }catch(IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

}
